package com.sql.controller;

import com.sql.model.BorrowInfo;
import com.sql.model.User;
import com.sql.service.BorrowInfoService;
import com.sql.service.UserService;
import com.sql.utils.MD5Util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

/**
 * Created by 走过全世界。 on 2017/5/26 0026.
 */
@Controller
//@RequestMapping("/login")
public class UserController {
    private static final Log logger = LogFactory.getLog(UserController.class);

    //    @Autowired
    private UserService userService;

    @Autowired
    private BorrowInfoService borrowInfoService;

    public UserService getUserService() {
        return userService;
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }


    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String register(@RequestParam("username") String username,
                           @RequestParam("password") String password,
                           @RequestParam("id_number") String id_number,
                           @RequestParam("email") String email,
                           @RequestParam("phone") String phone,
                           HttpServletRequest request,
                           HttpServletResponse response) {
        User user = userService.getUserByUsername(username);
        if (user == null) {
            user = new User(null, username, MD5Util.getMD5String(password), id_number, email, phone, 0);
            logger.info(user);
            Integer id = userService.insertNewUser(user);
            user.setId(id);
            request.getSession().setAttribute("user", user);
        } else {
            logger.info("--------->已存在，请重新输入");
            request.getSession().setAttribute("errorMessage", "当前用户已存在");
            return "register";
        }
        return "hello";
    }

    @RequestMapping(value = "/registerForm", method = RequestMethod.GET)
    public String registerForm() {
        logger.info("-------------->to registerForm");
        return "register";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        HttpServletRequest request,
                        HttpServletResponse response) throws IOException {
        User user = userService.getUserByUsername(username);
        if (user != null && user.getPassword().equals(MD5Util.getMD5String(password))) {
            logger.info("----------------->success");
            request.getSession().setAttribute("user", user);
            ArrayList<BorrowInfo> borrowedBooks = borrowInfoService.getBorrowedBooks(user.getUsername());
            request.setAttribute("borrowedBooks", borrowedBooks);
            return "hello";
        } else {
            logger.info("------------>" + username + ":" + password);
            response.setContentType("text/html;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Cache-Control", "no-cache");
            PrintWriter out = response.getWriter();
            out.println("<script language='javascript'>");
            out.println("alert('用户名或密码错误，请重新输入')");
            out.println("history.go(-1)");
            out.println("</script>");
            out.flush();
            out.close();
            out = null;
            //return null;
            return "login";
        }
    }

    @RequestMapping(value = "/loginForm", method = RequestMethod.GET)
    public String loginForm(HttpServletRequest request,
                            HttpServletResponse response) {
        logger.info("to loginForm");
        return "login";
    }

    @RequestMapping(value = "/hello")
    public String hello(@RequestParam("name") int name,
                        HttpServletRequest request,
                        HttpServletResponse response) {
        logger.info("hello:" + name);
        request.setAttribute("name", "zzl");
        request.getSession().setAttribute("hello", "lzt");
        return "hello";
    }

    @RequestMapping(value = "/query/{id}")
    public String hello(@PathVariable("id") Integer id,
                        HttpServletRequest request,
                        HttpServletResponse response) {
        User user = userService.getUserById(id);
        if (user != null)
            logger.info("---------->" + user);
        else
            logger.info("---------->null");
        return "hello";
    }
}
